package app.com.myudpateapp2.presenter;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;


import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import app.com.myudpateapp2.model.InfoBean;
import app.com.myudpateapp2.model.Model;
import app.com.myudpateapp2.model.UpdateInfo;
import app.com.myudpateapp2.view.MainActivity;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by asus on 2017/8/7.
 */

public class SettingPresenter {
    private Context context;
    private MainActivity view;
    private Model model;


    public SettingPresenter(Context context, MainActivity view){
        this.context = context;
        this.view = view;
    }

    public void updateAPK() {
        model = Model.getInstance();
        //需要修改
        model.get("http://api.test.daozijinfu.com/v2.0/Api/Index/getVersion/JDT_SID/7hapljg2hc61qv6kck8insb7f7/",new okhttp3.Callback(){
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseBody = response.body().string();
                StringBuffer sb = new StringBuffer();
                BufferedReader reader = null;
                UpdateInfo updateInfo = new UpdateInfo();
                Log.d("版本", "onResponse: "+responseBody);
                reader = new BufferedReader(new StringReader(responseBody));
                Log.d("=====read",reader.readLine());
                InfoBean bean = new Gson().fromJson(responseBody, InfoBean.class);
Log.d("=====bean",bean.getData().getVersion_number());
                  updateInfo.setVersion(bean.getData().getVersion_number());
                  updateInfo.setDescription(bean.getData().getUpdate_content());
                  updateInfo.setUrl(bean.getData().getFile_path());
                  String new_version = updateInfo.getVersion();
                  Log.d("版本", "onResponse: "+updateInfo.getVersion());
                  Log.d("版本描述", "onResponse: "+updateInfo.getDescription());
                  Log.d("更新链接", "onResponse: "+updateInfo.getUrl());
                String now_version = "";
                try {
                    PackageManager packageManager = context.getPackageManager();
                    PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),0);
                    now_version = packageInfo.versionName;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }

                if(now_version.equals(new_version)){
                    view.showError("");
                    Log.d("版本号是", "onResponse: "+now_version);
                }else{
                    view.showUpdateDialog(updateInfo);
                }
            }
        });
    }

    public void downFile(final String url) {
        Log.d("SettingPresenter", "downFile: ");
        model = Model.getInstance();
        model.get(url,new okhttp3.Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                view.downFial();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;//输入流
                FileOutputStream fos = null;//输出流
                try {
                    is = response.body().byteStream();//获取输入流
                    long total = response.body().contentLength();//获取文件大小
                    view.setMax(total);//为progressDialog设置大小
                    if(is != null){
                        Log.d("SettingPresenter", "onResponse: 不为空");
                        File file = new File(Environment.getExternalStorageDirectory(),"app.apk");// app名称，设置路径
                        fos = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int process = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fos.write(buf, 0, ch);
                            process += ch;
                            view.downLoading(process);       //这里就是关键的实时更新进度了！
                        }

                    }
                    fos.flush();
                    // 下载完成
                    if(fos != null){
                        fos.close();
                    }
                    //down();
                    view.downSuccess();
                    //view.showSuccess();
                } catch (Exception e) {
                    view.downFial();
                    Log.d("SettingPresenter",e.toString());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }

            //private void down() {
               // progressDialog.cancel();
           // }
        });
    }


    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}